package org.yoyo.classroom.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.yoyo.classroom.domain.po.BookingDTO;
import org.yoyo.classroom.domain.po.BookingOrder;
import org.yoyo.classroom.domain.po.ValidationResult;
import org.yoyo.classroom.result.Result;
import org.yoyo.classroom.service.BookingOrderService;
import org.yoyo.classroom.service.BookingValidationService;
import org.yoyo.classroom.util.BookingConverter;
import org.yoyo.classroom.utils.JwtTokenUtil;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/12/22/8:55
 **/
@RestController
@RequestMapping("/admin/order")
public class OrderController {
    @Autowired
    private BookingOrderService bookingOrderService;
    @Autowired
    private BookingValidationService validationService;
    /**
     * 创建预约
     *
     * 该方法用于接受前台自习室订单生成请求，并检验自习室预约规则。
     *
     * @param bookingDTO 包含预约信息的数据传输对象，包括用户ID、房间ID、预约日期、开始时间和结束时间。
     * @return 包含结果的信息，成功时返回“预约成功”，失败时返回错误信息。
     */
    /**
     * Create a booking
     *
     * This method is used to accept a study room booking request from the frontend and validate the booking rules.
     *
     * @param bookingDTO Data transfer object containing booking information, including user ID, room ID, booking date, start time, and end time.
     * @return Result containing the response information, returns "预约成功" on success, and error message on failure.
     */
    @PostMapping("/takeOrder")
    public Result createBooking(
            @RequestHeader(value = "Authorization", required = false) String authorizationHeader,
            @RequestBody BookingDTO bookingDTO) {
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        // 检查并解析 token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            // 2. 验证 Token
            String username = jwtTokenUtil.getUsernameFromToken(token);

            bookingDTO.setUserId(jwtTokenUtil.getUserIdFromToken(token));

        } else {

            return Result.error("Token 未提供");
        }


        // 1. 校验预约参数
        ValidationResult validationResult = validationService.validateBooking(bookingDTO);
        if (!validationResult.isSuccess()) {
            return Result.error(validationResult.getMessage());
        }
        // 2. 创建预约
        try {
            BookingOrder bookingOrder=new BookingOrder();
            bookingOrder=new BookingConverter().convertToBookingOrder(bookingDTO);
            int affectedRows = bookingOrderService.addBookingOrder(bookingOrder);
            return Result.success("预约成功");
        } catch (Exception e) {
            return Result.error("预约失败：" + e.getMessage());
        }
    }


}
